<?php
// +-------------------------------------------------------------------
// |
// +-------------------------------------------------------------------
// | Copyright (c) 2009-2016 All rights reserved.
// +-------------------------------------------------------------------
namespace Service\Ldap;

class Service
{
    static $instance;

    public static function getInstance()
    {
        if (self::$instance) {
            return self::$instance;
        }

        $link = \ldap_connect(LDAP_HOST, LDAP_PORT);
        if (!$link) {
            throw new \Exception('连接失败');
        }

        \ldap_set_option($link, LDAP_OPT_REFERRALS, 0);
        \ldap_set_option($link, LDAP_OPT_PROTOCOL_VERSION, 3);
        self::$instance = $link;
        return self::$instance;
    }


    //邮箱登录
    public function login($mail, $password, $getUserInfo = false)
    {
        $link = self::getInstance();
        $bind = \ldap_bind($link, $mail, $password);
        if (!$bind) {
            throw new \Exception('登录的邮箱或密码不对！');
        }
        return $getUserInfo ? $this->getUserInfo($mail) : true;
    }

    //获取用户信息
    public function getUserInfo($mail)
    {
        $link = self::getInstance();
        $bind = \ldap_bind($link, LDAP_RDN, LDAP_PASSWORD);
        if (!$bind) {
            throw new \Exception('查询的邮箱或密码不对');
        }

        $search = \ldap_search($link, "ou=先锋集团,dc=ucfgroup,dc=com", "(mail=$mail)");
        if (!$search) {
            throw new \Exception('没有找到该邮箱的用户信息');
        }

        $entry = ldap_get_entries($link, $search);

        $result ['name'] = $entry[0]['displayname'][0];
        $result ['department'] = $entry[0]['department'][0];
        $result ['mobile'] = $entry[0]['extensionattribute2'][0];
        $result ['mail'] = $entry[0]['mail'][0];
        $result ['no'] = $entry[0]['description'][0];
        $result ['dn'] = !empty($entry[0]['distinguishedName'][0]) ? $entry[0]['distinguishedName'][0] : $entry[0]['distinguishedname'][0];
        return $result;
    }
}
